import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getConfig, updateConfig } from '@/api/config';
import { ElMessage } from 'element-plus';

export const useSettingsStore = defineStore('settings', () => {
  // --- State ---
  // 使用ref定义响应式状态
  const config = ref({
    host: '',
    drivePort: null,
    analysisPort: null,
    cloudUrl: '',
    cam1: '', username1: '', password1: '',
    cam2: '', username2: '', password2: '',
    cam3: '', username3: '', password3: '',
    cam4: '', username4: '', password4: '',
  });

  const loading = ref(false);

  // --- Actions ---
  // 异步action，用于从后端获取配置
  const fetchConfig = async () => {
    loading.value = true;
    try {
      const response = await getConfig();
      console.log("config",response)
      if (response.data) {
        config.value = response.data.data;
      }
      return response;
    } catch (error) {
      ElMessage.error('获取系统配置失败！');
      console.error(error);
    } finally {
      loading.value = false;
    }
  };

  // 异步action，用于保存配置到后端
  const saveConfig = async (newConfig) => {
    loading.value = true;
    try {
      const response = await updateConfig(newConfig);
      // 保存成功后，更新本地state
      config.value = { ...newConfig };
      ElMessage.success('系统配置保存成功！');
      return response;
    } catch (error) {
      ElMessage.error('系统配置保存失败！');
      console.error(error);
      // 抛出错误，方便UI层捕获
      throw error;
    } finally {
      loading.value = false;
    }
  };

  // --- Getters ---
  // (此store暂不需要getters，但可以按需添加)
  // const agvApiBaseUrl = computed(() => `http://${config.value.host}:${config.value.drivePort}`);

  // 返回state和actions
  return {
    config,
    loading,
    fetchConfig,
    saveConfig,
  };
});